<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Model\Wxpay;

class Cash extends Model
{
	public static function cash_format(&$list){

		$uids = get_array_keys($list->items(),'uid');
		$users = DB::table('user_tree')->whereIn('uid',$uids)->get()->toArray();
		$users = arrays_set_key($users,'uid');

		$risk = DB::table('user_risk_level')->select(['uid','riskReason'])->whereIn('uid',$uids)->get()->toArray();
		$risk = arrays_set_key($risk,'uid');

		foreach($list->items() as $item){
			$item->user = $users[$item->uid];
			$tdids = DB::table('user_tree')->where([
				['pid','=',$item->uid]
			])->pluck('uid')->toArray();

			$item->td_huoyue = DB::table('everyday_contribution')->select(DB::raw('count(id) as count,uid'))
            ->whereIn('uid',$tdids)
            ->where([
                ['day','=',date('Ymd',strtotime("-1 day"))],
                ['frequency_all','>',2]
            ])->count();

            $item->riskReason = $risk[$item->uid]->riskReason??'';
		}
	}

	/**
	 * 合伙人提现
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function wx_pay($id){
		try {
			DB::beginTransaction();
			$info = DB::table('partner_cash')->where('id',$id)->where('pay_status',0)->lockForUpdate()->first();
			if(empty($info)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'提现信息不存在或者状态为不可付款'];	
			}
			$user = DB::table('user_tree')->where('uid',$info->uid)->lockForUpdate()->first(['money']);
			$userdata = DB::table('userdata')->where('id',$info->uid)->first(['openid']);
			if(empty($userdata->openid)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'用户还没有绑定微信号'];
			}
			if($info->state!=1){
				DB::rollBack();
				return ['status'=>0,'msg'=>'提现未审核通过/或者已经失败过'];
			}
			$step1 = DB::table('partner_cash')->where('id',$id)->update([
				'pay_status'=>1,
				'pay_time'=>time(),
			]);
			$step2 = DB::table('partner_moneylog')->insert([
				'uid'=>$info->uid,
				'affect'=>-$info->money,
				'current_money'=>$user->money - $info->money,
				'add_time'=>time(),
			]);
			$step3 = DB::table('user_tree')->where('uid',$info->uid)->update([
				'money'=>DB::raw("`money`-".$info->money),
			]);
			if( $step1!==false && $step2!==false && $step3!==false ){
				$rs = (new Wxpay())->cash([
					'partner_trade_no'=>$info->trad_no,
					'openid'=>$userdata->openid,
					'amount'=>$info->money,
					'spbill_create_ip'=>$info->ip,
					're_user_name'=>$info->real_name,
					'desc'=>'合伙人提现',
				]);
				if($rs['return_code']!='SUCCESS'){
					DB::rollBack();
					return ['status'=>0,'msg'=>$rs['err_code_des'],'data'=>$rs];
				}
				if($rs['result_code']=='SUCCESS'){
					DB::commit();
					DB::table('partner_cash')->where('id',$id)->update([
						'payment_no'=>$rs['payment_no'],
					]);
					return ['status'=>1,'msg'=>''];
				}else{
					DB::rollBack();
					#提现失败退回资金
					DB::beginTransaction();
					$info = DB::table('partner_cash')->where('id',$id)->where('pay_status',0)->lockForUpdate()->first();
					$user = DB::table('user_tree')->where('uid',$info->uid)->lockForUpdate()->first(['money']);
					$refund1 = DB::table('partner_cash')->where('id',$id)->update(['pay_status'=>2,'desc'=>$rs['err_code_des']]);
					$refund2 = DB::table('partner_moneylog')->insert([
						'uid'=>$info->uid,
						'affect'=>$info->money,
						'add_time'=>time(),
						'current_money'=>$user->money+$info->money,
						'type'=>2,
					]);
					$refund3 = DB::table('user_tree')->where('uid',$info->uid)->update([
						'money'=>DB::raw("`money`+".$info->money),
					]);
					
					if( $refund1!==false && $refund2!==false && $refund3!==false ){
						DB::commit();
						return ['status'=>0,'msg'=>"付款失败，提现已取消",'data'=>$rs];
					}else{
						DB::rollBack();
						return ['status'=>0,'msg'=>'事物回滚','data'=>$rs];
					}
				}
			}
		} catch (\Exception $e) {
			DB::rollBack();
			return ['status'=>0,'msg'=>$e->getMessage()];
		}
		
	}

	/**
	 * 普通会员提现
	 * @return [type] [description]
	 */
	public function tx($id){
		try {
			DB::beginTransaction();
			$info = DB::table('txdata')->where('id',$id)->lockForUpdate()->first();
			if(empty($info)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'提现不存在'];
			}
			if($info->state!=3 && $info->state!=4){
				DB::rollBack();
				return ['status'=>0,'msg'=>'当前提现状态为不可付款,state:'.$info->state];
			}
			$userdata = DB::table('userdata')->where('id',$info->uid)->first(['money','openid']);
			if(empty($userdata->openid)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'用户还没有绑定微信号'];
			}

			$step1 = DB::table('txdata')->where('id',$id)->update(['state'=>1]);
			if(DB::table('wx_tx_order')->where('partner_trade_no',$info->trad_no)->exists()) {
				$step2 = DB::table('wx_tx_order')->where('partner_trade_no',$info->trad_no)->update([
					'u_id'=>$info->uid,
					'tx_id'=>$id,
					'partner_trade_no'=>$info->trad_no,
					'user_name'=>$info->real_name,
					'openid'=>$info->payment_account,
					'money'=>$info->money,
					'stats'=>1,
					'cause'=>'',
					'add_time'=>time(),
				]);
			}else{
				$step2 = DB::table('wx_tx_order')->insert([
					'u_id'=>$info->uid,
					'tx_id'=>$id,
					'partner_trade_no'=>$info->trad_no,
					'user_name'=>$info->real_name,
					'openid'=>$info->payment_account,
					'money'=>$info->money,
					'stats'=>1,
					'cause'=>'',
					'add_time'=>time(),
				]);
			}
			
			if( $step1!==false && $step2!==false ){
				$rs = (new Wxpay())->cash([
					'partner_trade_no'=>$info->trad_no,
					'openid'=>$info->payment_account,
					'amount'=>$info->money,
					'spbill_create_ip'=>'127.0.0.1',
					're_user_name'=>$info->real_name,
					'desc'=>'用户提现',
				]);
				if($rs['return_code']!='SUCCESS'){
					DB::rollBack();
					return ['status'=>0,'msg'=>$rs['err_code_des'],'data'=>$rs];
				}
				if($rs['result_code']=='SUCCESS'){
					DB::commit();
					return ['status'=>1,'msg'=>''];
				}else{
					DB::rollBack();
					#取消提现
					DB::beginTransaction();
					if(DB::table('wx_tx_order')->where('partner_trade_no',$info->trad_no)->exists()) {
						$refund1 = DB::table('wx_tx_order')->where('partner_trade_no',$info->trad_no)->update([
							'stats'=>0,
							'cause'=>$rs['err_code_des'],
							'add_time'=>time(),
						]);
					}else{
						$refund1 = DB::table('wx_tx_order')->insert([
							'u_id'=>$info->uid,
							'tx_id'=>$id,
							'partner_trade_no'=>$info->trad_no,
							'user_name'=>$info->real_name,
							'openid'=>$info->payment_account,
							'money'=>$info->money,
							'stats'=>0,
							'cause'=>$rs['err_code_des'],
							'add_time'=>time(),
						]);
					}

					
					$divide_into_state = 1;
					$refund3 = true;
					if( in_array($rs['err_code_des'], ['openid与商户appid不匹配','真实姓名不一致','真实姓名不一致.','非实名用户账号不可发放','V2_ACCOUNT_SIMPLE_BAN'] ) ){
						$state = 5;
						$divide_into_state = 0;
						$refund3 = DB::table('userdata')->where('id',$info->uid)->update(['money'=>DB::raw("`money`+".$info->money)]);
					}else{
						$state = $info->state==4?6:4;
						if($state==6) {
							$refund3 = DB::table('userdata')->where('id',$info->uid)->update(['money'=>DB::raw("`money`+".$info->money)]);
						}
					}

					$refund2 = DB::table('txdata')->where('id',$id)->update(['state'=>$state,'divide_into_state'=>$divide_into_state]);

					if($refund1!==false && $refund2!==false && $refund3!==false){
						DB::commit();
						return ['status'=>0,'msg'=>"付款失败，提现已取消",'data'=>$rs];
					}else{
						DB::rollBack();
						return ['status'=>0,'msg'=>'事物回滚','data'=>$rs];
					}
				}
			}
		} catch (\Exception $e) {
			DB::rollBack();
			return ['status'=>0,'msg'=>$e->getMessage()];
		}
	}



	/**
	 * 普通用户支付宝提现
	 * @return [type] [description]
	 */
	public function tx_alipay($id){
		try {
			DB::beginTransaction();
			$info = DB::table('txdata')->where('id',$id)->lockForUpdate()->first();
			if(empty($info)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'提现不存在'];
			}
			if($info->state!=3 && $info->state!=4){
				DB::rollBack();
				return ['status'=>0,'msg'=>'当前提现状态为不可付款,state:'.$info->state];
			}
			$userdata = DB::table('userdata')->where('id',$info->uid)->first(['money','openid']);
			if(empty($userdata->openid)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'用户还没有绑定微信号'];
			}

			$step1 = DB::table('txdata')->where('id',$id)->update(['state'=>1]);
			if(DB::table('zfb_tx_order')->where('out_biz_no', $info->trad_no)->exists() ){
				DB::table('zfb_tx_order')->where('out_biz_no', $info->trad_no)->update([
					'uid'=>$info->uid,
					'tx_id'=>$id,
					'realname'=>$info->real_name,
					'alipay'=>$info->payment_account,
					'money'=>$info->money,
					'status'=>1,
					'message'=>'',
					'time'=>time(),
				]);
			}else{
				$step2 = DB::table('zfb_tx_order')->insert([
					'uid'=>$info->uid,
					'tx_id'=>$id,
					'out_biz_no'=>$info->trad_no,
					'realname'=>$info->real_name,
					'alipay'=>$info->payment_account,
					'money'=>$info->money,
					'status'=>1,
					'message'=>'',
					'time'=>time(),
				]);
			}
			
			if( $step1!==false && $step2!==false ){
				$rs = (new Alipay())->pay([
					'out_biz_no'=>$info->trad_no,
					'payee_account'=>$info->payment_account,
					'amount'=>$info->money,
					'payee_real_name'=>$info->real_name,
				]);
		
				if($rs['status']==1){
					DB::commit();
					return ['status'=>1,'msg'=>''];
				}else{
					DB::rollBack();
					#取消提现
					DB::beginTransaction();
					if(DB::table('zfb_tx_order')->where('out_biz_no', $info->trad_no)->exists() ){
						$refund1 = DB::table('zfb_tx_order')->where('out_biz_no', $info->trad_no)->update([
							'uid'=>$info->uid,
							'tx_id'=>$id,
							'realname'=>$info->real_name,
							'alipay'=>$info->payment_account,
							'money'=>$info->money,
							'status'=>0,
							'message'=>'',
							'time'=>time(),
						]);
					}else{
						$refund1 = DB::table('zfb_tx_order')->insert([
							'uid'=>$info->uid,
							'tx_id'=>$id,
							'out_biz_no'=>$info->trad_no,
							'realname'=>$info->real_name,
							'alipay'=>$info->payment_account,
							'money'=>$info->money,
							'status'=>0,
							'message'=>'',
							'time'=>time(),
						]);
					}
					

					
					$divide_into_state = 1;
					$refund3 = true;
				
					if($rs['state']==5){
						$state = 5;
						$divide_into_state = 0;
						$refund3 = DB::table('userdata')->where('id',$info->uid)->update(['money'=>DB::raw("`money`+".$info->money)]);
					}else{
						$state = $info->state==4?6:4;
						$refund3 = DB::table('userdata')->where('id',$info->uid)->update(['money'=>DB::raw("`money`+".$info->money)]);
					}
					$refund2 = DB::table('txdata')->where('id',$id)->update(['state'=>$state,'divide_into_state'=>$divide_into_state]);

					if($refund1!==false && $refund2!==false && $refund3!==false){
						DB::commit();
						return ['status'=>0,'msg'=>"付款失败，提现已取消",'data'=>$rs];
					}else{
						DB::rollBack();
						return ['status'=>0,'msg'=>'事物回滚','data'=>$rs];
					}
				}
			}
		} catch (\Exception $e) {
			DB::rollBack();
			return ['status'=>0,'msg'=>$e->getMessage()];
		}
	}

	/**
	 * 合伙人支付宝提现
	 */
	public function partner_pay($id){
		try {
			DB::beginTransaction();
			$info = DB::table('partner_cash')->where('id',$id)->where('pay_status',0)->lockForUpdate()->first();
			if(empty($info)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'提现信息不存在或者状态为不可付款'];	
			}
			$user = DB::table('user_tree')->where('uid',$info->uid)->lockForUpdate()->first(['money']);
			$userdata = DB::table('userdata')->where('id',$info->uid)->first(['openid']);
			if(empty($userdata->openid)){
				DB::rollBack();
				return ['status'=>0,'msg'=>'用户还没有绑定微信号'];
			}
			if($info->state!=1){
				DB::rollBack();
				return ['status'=>0,'msg'=>'提现未审核通过/或者已经失败过'];
			}
			$step1 = DB::table('partner_cash')->where('id',$id)->update([
				'pay_status'=>1,
				'pay_time'=>time(),
			]);
			$step2 = DB::table('partner_moneylog')->insert([
				'uid'=>$info->uid,
				'affect'=>-$info->money,
				'current_money'=>$user->money - $info->money,
				'add_time'=>time(),
			]);
			$step3 = DB::table('user_tree')->where('uid',$info->uid)->update([
				'money'=>DB::raw("`money`-".$info->money),
			]);
			if( $step1!==false && $step2!==false && $step3!==false ){
				$rs = (new Alipay())->pay([
					'out_biz_no'=>$info->trad_no,
					'payee_account'=>$info->payment_account,
					'amount'=>$info->money,
					'payee_real_name'=>$info->real_name,
				]);
			
				if($rs['status']==1){
					DB::commit();
					DB::table('partner_cash')->where('id',$id)->update([
						'payment_no'=>$rs['order_id'],
					]);
					return $rs;
				}else{
					DB::rollBack();
					#提现失败退回资金
					DB::beginTransaction();
					$info = DB::table('partner_cash')->where('id',$id)->where('pay_status',0)->lockForUpdate()->first();
					$user = DB::table('user_tree')->where('uid',$info->uid)->lockForUpdate()->first(['money']);
					$refund1 = DB::table('partner_cash')->where('id',$id)->update(['pay_status'=>2,'desc'=>$rs['data']['err_code_des']]);
					$refund2 = DB::table('partner_moneylog')->insert([
						'uid'=>$info->uid,
						'affect'=>$info->money,
						'add_time'=>time(),
						'current_money'=>$user->money+$info->money,
						'type'=>2,
					]);
					$refund3 = DB::table('user_tree')->where('uid',$info->uid)->update([
						'money'=>DB::raw("`money`+".$info->money),
					]);
					
					if( $refund1!==false && $refund2!==false && $refund3!==false ){
						DB::commit();
						return ['status'=>0,'msg'=>"付款失败，提现已取消",'data'=>$rs];
					}else{
						DB::rollBack();
						return ['status'=>0,'msg'=>'事物回滚','data'=>$rs];
					}
				}
			}
		} catch (\Exception $e) {
			DB::rollBack();
			return ['status'=>0,'msg'=>$e->getMessage()];
		}
	}
}